import { DataSource } from 'typeorm'
import { initDataBase } from './DataBaseBuilder'
import { BetterSqlite3ConnectionOptions } from 'typeorm/driver/better-sqlite3/BetterSqlite3ConnectionOptions'
import { UserInfo } from './entities/UserInfo'

export class DataBaseManager {
  static mainDataSource: DataSource
  static mainDataSourceOption: BetterSqlite3ConnectionOptions = {
    type: 'better-sqlite3',
    entities: [UserInfo],
    database: 'data/db/data.db',
    synchronize: true,
  }

  static init() {
    return new Promise((resolve) => {
      this.getMainDataSource().then(() => {
        resolve('ok')
      })
    })
  }

  static getMainDataSource() {
    return new Promise<DataSource>((resolve,reject) => {
      if (!this.mainDataSource) {
        initDataBase(this.mainDataSourceOption).then((dataSource) => {
          this.mainDataSource = dataSource
          resolve(this.mainDataSource)
        })
          .catch(e=>{
            reject(e)
          })
      } else {
        resolve(this.mainDataSource)
      }
    })
  }
}
